﻿using Kernelx.Contexts.Core; 
using System;
 
namespace Kernelx.Contexts
{ 
    /// <summary>
    /// 
    /// </summary>
    public static class WorkloadContextExtensions
    {
         
        #region 扩展GetService<>的快捷调用方法
         
        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <param name="serviceType"></param>
        /// <param name="customErrMsg"></param>
        /// <returns></returns>
        /// <exception cref="ApplicationException"></exception>
        public static object GetRequiredService(this IWorkloadContext context, Type serviceType, string customErrMsg = null) => context.GetService(serviceType) ??
            throw new ApplicationException(string.IsNullOrEmpty(customErrMsg) ? $"无法从上下文获取指定类型[{serviceType.FullName}]的实例." : customErrMsg);

        /// <summary>
        /// 
        /// </summary> 
        /// <typeparam name="T"></typeparam>
        /// <param name="context"></param>
        /// <returns></returns>
        public static T GetService<T>(this IWorkloadContext context) where T : class => context.GetService(typeof(T)) as T;


        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="context"></param>
        /// <param name="customErrMsg"></param>
        /// <returns></returns>
        public static T GetRequiredService<T>(this IWorkloadContext context, string customErrMsg = null) where T : class
            => context.GetRequiredService(typeof(T), customErrMsg) as T;

        #endregion
        
    }
}
